//
//  AY_SearchViewController.m
//  AiYue
//
//  Created by mac on 2023/11/3.
//

#import "AY_SearchViewController.h"
#import "AY_SearchKeyCell.h"
#import "AY_SearchKeyView.h"
#import "AY_SearchRecommonCell.h"
#import "AY_ThinkTableView.h"
#import "AY_SearchResultView.h"
#import "AY_BookDetailViewController.h"

@interface AY_SearchViewController ()<UITextFieldDelegate, SXLoadingDelegate, SXthinkViewDelegate, SXSearchKeyDelegate>

@property (nonatomic, strong) UITextField *searchField;
@property (strong,nonatomic) UIView *searchView;
@property (strong,nonatomic) NSMutableArray *hotKeys;
@property (strong,nonatomic) NSMutableArray *recommends;
@property (strong,nonatomic) NSMutableArray *books;
@property (strong,nonatomic) NSMutableArray *thinks;
@property (assign,nonatomic) BOOL isSearch;
@property (strong,nonatomic) AY_ThinkTableView *thinkTable;
@property (strong,nonatomic) AY_LoadingView *loadingView;
@property (strong,nonatomic) UIButton *cleanBtn;
@property (strong,nonatomic) AY_SearchResultView *searcgResultView;
@property (strong,nonatomic) NSMutableArray *historyDatas;
@property (strong,nonatomic) ConfigModel *configModel;
@end

@implementation AY_SearchViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self getHistoryDatas];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [self.searchField becomeFirstResponder];
}

- (void)getHistoryDatas {
    NSData *data = [NSKeyedArchiver archivedDataWithRootObject:@[]];
    NSData *historyData = [AYMMKV getDataForKey:HistoryData defaultValue:data];
    self.historyDatas = [NSMutableArray arrayWithArray:[NSKeyedUnarchiver unarchiveObjectWithData:historyData]];
    [self.tableView reloadData];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.isSearch = NO;
    self.tableView.frame = CGRectMake(0, GK_STATUSBAR_NAVBAR_HEIGHT, SCREEN_W, SCREEN_H - GK_STATUSBAR_NAVBAR_HEIGHT);
    self.gk_navBackgroundColor = COLOR(@"#F7F5F6");
    self.tableView.backgroundColor = COLOR(@"#F7F5F6");
    [self setNavView];
    [self loadData];
}

- (void)loadData {
    
    dispatch_group_t group = dispatch_group_create();
    
    dispatch_group_enter(group);
    [AYApiRequest getSearchHotKeyWithLimit:@"0" Success:^(AY_SearchKeyModel * _Nonnull pkg) {
        self.hotKeys = [NSMutableArray arrayWithArray:pkg.data];
        dispatch_group_leave(group);
    } failure:^(int status, NSString * _Nonnull info) {
        dispatch_group_leave(group);
    }];
    
    dispatch_group_enter(group);
    [AYApiRequest getSearchRecommengWithLimit:@"0" Success:^(AY_SearchModel * _Nonnull pkg) {
        self.recommends = [NSMutableArray arrayWithArray:pkg.data];
        dispatch_group_leave(group);
    } failure:^(int status, NSString * _Nonnull info) {
        dispatch_group_leave(group);
    }];
    
    dispatch_group_enter(group);
    [AYApiRequest APPConfigSuccess:^(AY_ConfigModel * _Nonnull pkg) {
        self.configModel = pkg.data;
        self.searcgResultView.configModel = self.configModel;
        dispatch_group_leave(group);
    } failure:^(int status, NSString * _Nonnull info) {
        dispatch_group_leave(group);
    }];
    
    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
        [self.tableView reloadData];
    });
}

- (void)setNavView {
    UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 60, 44)];
    [btn setTitle:@"搜索     " forState:UIControlStateNormal];
    [btn setTitleColor:COLOR(@"000002") forState:UIControlStateNormal];
    btn.titleLabel.font = YFont(14);
    self.gk_navRightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:btn];
    [btn addTarget:self action:@selector(goToSearch) forControlEvents:UIControlEventTouchUpInside];
    
    UIView *searchView = [[UIView alloc] initWithFrame:CGRectMake(0, -YNUM(10), SCREEN_W - YNUM(50), YNUM(34))];
    searchView.backgroundColor = COLOR(@"EAEEF7");
    searchView.layer.masksToBounds = YES;
    searchView.layer.cornerRadius = YNUM(17);
    self.gk_navTitleView = searchView;
    UIImageView *icon;
    icon = [AYTool createImageViewWithFrame:CGRectMake(YNUM(12), (searchView.mj_h/2) - YNUM(8), YNUM(16), YNUM(16)) andImage:YImage(@"AY_search_icon") andBg:nil andRadius:0 andAddSubView:searchView];
    self.cleanBtn = [AYTool createButtonWithFrame:CGRectMake(SCREEN_W - 140, (searchView.mj_h/2) - YNUM(8), YNUM(16), YNUM(16)) andTitle:nil andFont:nil andTitleColor:nil andBg:nil andImage:nil andBgImage:YImage(@"AY_search_clean") andTarget:self andAction:@selector(cleanAction) andRadius:0 andAddSubView:searchView];
    self.cleanBtn.hidden = YES;
    
    _searchField = [[UITextField alloc] initWithFrame:CGRectMake(YNUM(36), 0, SCREEN_W - YNUM(170), searchView.mj_h)];
    _searchField.placeholder = @"搜索书名、作者";
    _searchField.delegate = self;
    _searchField.returnKeyType = UIReturnKeySearch;
    [_searchField addTarget:self action:@selector(textFieldEditChanged:) forControlEvents:UIControlEventEditingChanged];
    _searchField.font = YFont(14);
    [searchView addSubview:_searchField];
}

- (void)cleanAction {
    [self getHistoryDatas];
    self.cleanBtn.hidden = YES;
    self.searchField.text = @"";
    [self textFieldEditChanged:self.searchField];
    [self.loadingView dismiss];
    [self.thinkTable dismiss];
    [self.searcgResultView dismiss];
    self.gk_navBackgroundColor = COLOR_Bg;
}

- (void)goToSearch {
    [self.searchField resignFirstResponder];
    NSString *searchText = self.searchField.text;
    searchText = [searchText stringByReplacingOccurrencesOfString:@" " withString:@""];
    searchText = [searchText stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    NSData* data = [self.configModel.search_filter dataUsingEncoding:NSUTF8StringEncoding];
    NSMutableArray *arr = data == nil ? [NSMutableArray arrayWithArray:@[]] : [NSJSONSerialization JSONObjectWithData:data options:nil error:nil];
    for (int i =0; i < arr.count; i++) {
        NSDictionary *dic = arr[i];
        searchText = [searchText stringByReplacingOccurrencesOfString:dic[@"oldChar"] withString:dic[@"newChar"]];
    }
    if (![searchText isEqualToString:@""]) {
        self.cleanBtn.hidden = NO;
        [self.loadingView loadingInView:self.view];
        
        [self setHistoryData];
        NSString *searchTtype = @"0";
        if ([AYMMKV getBoolForKey:ISSHENHE defaultValue:YES]) {
            searchTtype = @"1";
        }
        [AYApiRequest getSearchBookListWithLimit:searchTtype andQk:self.searchField.text Success:^(AY_SearchModel * _Nonnull pkg) {
            [self.loadingView dismiss];
            NSMutableArray *books = [NSMutableArray arrayWithArray:pkg.data];
            if (books.count == 1) {
                AY_BookDetailViewController *bookDetailVC = [[AY_BookDetailViewController alloc] init];
                bookDetailVC.bookId = [books[0] bookId];
                [self.navigationController pushViewController:bookDetailVC animated:YES];
            }
            [self.searcgResultView sendBooks:books andSearchKey:self.searchField.text];
            [self.searcgResultView loadingInView:self.view];
            self.gk_navBackgroundColor = [UIColor whiteColor];
        } failure:^(int status, NSString * _Nonnull info) {
            [self.loadingView refresh];
            [self.searcgResultView dismiss];
            self.gk_navBackgroundColor = COLOR_Bg;
        }];
    }else{
        self.searchField.text = @"";
        ShowToast(@"请输入搜索内容");
    }
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    [self.view endEditing:YES];
}

- (void)setHistoryData {
    NSData *data = [NSKeyedArchiver archivedDataWithRootObject:@[]];
    NSData *historyData = [AYMMKV getDataForKey:HistoryData defaultValue:data];
    NSMutableArray *historys = [NSMutableArray arrayWithArray:[NSKeyedUnarchiver unarchiveObjectWithData:historyData]];
    [historys addObject:self.searchField.text];
    NSSet *set = [NSSet setWithArray:historys.copy];
    NSArray *newArray = [set allObjects];
    data = [NSKeyedArchiver archivedDataWithRootObject:newArray];
    [AYMMKV setData:data forKey:HistoryData];
}

- (void)refreshAction {
    [self goToSearch];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [self goToSearch];
    return YES;
}

- (void)textFieldEditChanged:(UITextField *)textField {
    self.isSearch = ![self isEmpty:textField.text];
    if (self.isSearch) {
        self.cleanBtn.hidden = NO;
        [self.thinkTable loadingInView:self.view];
        NSString *searchTtype = @"0";
        if ([AYMMKV getBoolForKey:ISSHENHE defaultValue:YES]) {
            searchTtype = @"1";
        }
        [AYApiRequest getSearchThinkWithLimit:searchTtype andQk:textField.text Success:^(AY_SearchKeyModel * _Nonnull pkg) {
            self.thinks = [NSMutableArray arrayWithArray:pkg.data];
            [self.thinkTable sendThinks:self.thinks andThinkKey:textField.text];
        } failure:^(int status, NSString * _Nonnull info) {
            ShowToast(@"亲，网络不顺畅哟~");
        }];
    }else {
        self.cleanBtn.hidden = YES;
        [self.thinkTable dismiss];
    }
}

- (void)didSelectRowAtString:(NSString *)text {
    self.searchField.text = text;
    [self goToSearch];
}

- (void)didSelectWithKey:(NSString *)text {
    self.searchField.text = text;
    [self goToSearch];
}

//判断是否全是空格
- (BOOL)isEmpty:(NSString *)str {

    if (!str) {

        return true;

    } else {

        NSCharacterSet *set = [NSCharacterSet whitespaceAndNewlineCharacterSet];

        NSString *trimedString = [str stringByTrimmingCharactersInSet:set];

        if ([trimedString length] == 0) {

            return true;

        } else {

            return false;

        }

    }

}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 3;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.row == 0) {
        if (self.historyDatas.count == 0) {
            static NSString *ID = @"UITableViewCell";
            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
            if (cell == nil) {
                cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
            }
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            return cell;
        }else {
            static NSString *ID = @"AY_SearchKeyCell";
            AY_SearchKeyCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
            if (cell == nil) {
                cell = [[AY_SearchKeyCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
            }
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.delegate = self;
            [cell sendInfo:@"搜索历史" andDataSource:self.historyDatas];
            return cell;
        }
    } else if (indexPath.row == 1) {
        if (self.hotKeys.count == 0) {
            static NSString *ID = @"UITableViewCell";
            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
            if (cell == nil) {
                cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
            }
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            return cell;
        }else {
            static NSString *ID = @"AY_SearchKeyCell";
            AY_SearchKeyCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
            if (cell == nil) {
                cell = [[AY_SearchKeyCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
            }
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.delegate = self;
            [cell sendInfo:@"搜索发现" andDataSource:self.hotKeys];
            return cell;
        }
    } else {
        static NSString *ID = @"AY_SearchRecommonCell";
        AY_SearchRecommonCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
        if (cell == nil) {
            cell = [[AY_SearchRecommonCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.recommends = self.recommends;
        return cell;
    }
}

- (void)deleteData {
    NSData *data = [NSKeyedArchiver archivedDataWithRootObject:@[]];
    self.historyDatas = [NSMutableArray arrayWithArray:[NSKeyedUnarchiver unarchiveObjectWithData:data]];
    [self.tableView reloadData];
    [AYMMKV setData:data forKey:HistoryData];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0) {
        if (self.historyDatas.count == 0) {
            return 0.0001;
        }else {
            float height = [AY_SearchKeyView getTagsViewHeight:self.historyDatas dic:@{@"type":@"1"}];
            return height+YNUM(40);
        }
    } else if (indexPath.row == 1) {
        if (self.hotKeys.count == 0) {
            return 0.0001;
        }else {
            float height = [AY_SearchKeyView getTagsViewHeight:self.hotKeys dic:@{@"type":@"1"}];
            return height+YNUM(40);
        }
    } else {
        return (YNUM(72)*self.recommends.count) + YNUM(86);
    }
}

- (NSMutableArray *)hotKeys {
    if (!_hotKeys) {
        _hotKeys = [NSMutableArray array];
    }
    return _hotKeys;
}

- (NSMutableArray *)recommends {
    if (!_recommends) {
        _recommends = [NSMutableArray array];
    }
    return _recommends;
}

- (NSMutableArray *)books {
    if (!_books) {
        _books = [NSMutableArray array];
    }
    return _books;
}

- (NSMutableArray *)thinks {
    if (!_thinks) {
        _thinks = [NSMutableArray array];
    }
    return _thinks;
}

- (AY_ThinkTableView *)thinkTable {
    if (!_thinkTable) {
        _thinkTable = [[AY_ThinkTableView alloc] initWithFrame:CGRectMake(0, GK_STATUSBAR_NAVBAR_HEIGHT, SCREEN_W, SCREEN_H - GK_STATUSBAR_NAVBAR_HEIGHT)];
        _thinkTable.backgroundColor = COLOR(@"#F7F5F6");
        _thinkTable.delegate = self;
    }
    return _thinkTable;
}

- (AY_LoadingView *)loadingView {
    if (!_loadingView) {
        _loadingView = [[AY_LoadingView alloc] initWithFrame:CGRectMake(0, GK_STATUSBAR_NAVBAR_HEIGHT, SCREEN_W, SCREEN_H - GK_STATUSBAR_NAVBAR_HEIGHT)];
        _loadingView.backgroundColor = COLOR(@"#F7F5F6");
        _loadingView.delegate = self;
    }
    return _loadingView;
}

- (AY_SearchResultView *)searcgResultView {
    if (!_searcgResultView) {
        _searcgResultView = [[AY_SearchResultView alloc] initWithFrame:CGRectMake(0, GK_STATUSBAR_NAVBAR_HEIGHT, SCREEN_W, SCREEN_H - GK_STATUSBAR_NAVBAR_HEIGHT)];
        _searcgResultView.backgroundColor = [UIColor whiteColor];
    }
    return _searcgResultView;
}
@end
